// pages/imageDetail/index.ts
interface UserInfo {
  nickName: string;
  avatarUrl: string;
}

interface ImageDetail {
  id: string;
  prompt: string;
  imageUrl: string;
  createdAt: number;
  user?: UserInfo;
}

Page({
  data: {
    image: null as ImageDetail | null,
    isLoading: true,
    errorMsg: ''
  },

  onLoad(options: { id: string }) {
    console.log('Image Detail page loaded with ID:', options.id);
    
    if (!options.id) {
      this.setData({
        isLoading: false,
        errorMsg: '图片ID不存在'
      });
      return;
    }
    
    // 获取通过导航传递的参数
    const eventChannel = this.getOpenerEventChannel();
    
    // 尝试获取通过页面传递的图片数据
    eventChannel.on('passImageData', (data: { image: ImageDetail }) => {
      if (data && data.image) {
        console.log('Received image data:', data.image);
        this.setData({
          image: data.image,
          isLoading: false
        });
      } else {
        // 如果没有传递图片数据，则需要从数据库加载
        this.loadImageById(options.id);
      }
    });
    
    // 检查是否通过事件传递了数据，如果没有，则直接加载
    if (!this.data.image && options.id) {
      setTimeout(() => {
        if (this.data.isLoading) {
          this.loadImageById(options.id);
        }
      }, 500);
    }
  },
  
  // 根据ID从数据库加载图片
  loadImageById(imageId: string) {
    this.setData({ isLoading: true });
    
    const db = wx.cloud.database();
    
    db.collection('images').doc(imageId).get().then(res => {
      console.log('Image loaded from database:', res.data);
      
      if (res.data) {
        // 查询创建者信息
        this.loadUserInfo(res.data.userId, res.data);
      } else {
        this.setData({
          isLoading: false,
          errorMsg: '图片不存在或已被删除'
        });
      }
    }).catch(err => {
      console.error('Failed to load image:', err);
      this.setData({
        isLoading: false,
        errorMsg: '加载图片失败'
      });
    });
  },
  
  // 加载用户信息
  loadUserInfo(userId: string, imageData: any) {
    const db = wx.cloud.database();
    
    db.collection('users').doc(userId).get().then(res => {
      console.log('User loaded from database:', res.data);
      
      const createdAt = imageData.createdAt ? new Date(imageData.createdAt).getTime() : Date.now();
      
      this.setData({
        image: {
          id: imageData._id,
          prompt: imageData.prompt,
          imageUrl: imageData.imageUrl,
          createdAt: createdAt,
          user: {
            nickName: res.data.nickName || '未知用户',
            avatarUrl: res.data.avatarUrl || ''
          }
        },
        isLoading: false
      });
    }).catch(err => {
      console.error('Failed to load user info:', err);
      
      // 即使用户信息加载失败，也显示图片
      this.setData({
        image: {
          id: imageData._id,
          prompt: imageData.prompt,
          imageUrl: imageData.imageUrl,
          createdAt: imageData.createdAt ? new Date(imageData.createdAt).getTime() : Date.now(),
          user: {
            nickName: '未知用户',
            avatarUrl: ''
          }
        },
        isLoading: false
      });
    });
  },
  
  // 预览大图
  previewImage() {
    if (!this.data.image) return;
    
    wx.previewImage({
      urls: [this.data.image.imageUrl],
      current: this.data.image.imageUrl
    });
  },
  
  // 返回上一页
  onBack() {
    wx.navigateBack();
  },
  
  // 格式化日期
  formatDate(timestamp: number): string {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }
}); 